package bean.managed;

import entity.CreditTermEntity;
import bean.managed.util.JsfUtil;
import bean.session.CreditTermEntityFacade;

import bean.session.CustomerAccountEntityFacade;
import entity.CustomerAccountEntity;
import exception.CannotDeleteDefaultCreditTermException;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;

@ManagedBean(name = "creditTermEntityController")
@SessionScoped
public class CreditTermEntityController extends AbstractBacking implements Serializable {

    private CreditTermEntity current;
    private CreditTermEntity oldCreditTerm;
    private List<CreditTermEntity> items = null;
    @EJB
    private bean.session.CreditTermEntityFacade ejbFacade;
    @EJB
    private CustomerAccountEntityFacade accountFacade;
    @ManagedProperty(value = "#{customerAccountEntityController}")
    private CustomerAccountEntityController customerAccountController;

    public CreditTermEntityController() {
    }

    public CreditTermEntity getSelected() {
        if (current == null) {
            current = new CreditTermEntity();
        }
        return current;
    }

    public CreditTermEntity getCurrent() {
        return current;
    }

    public void setCurrent(CreditTermEntity current) {
        this.current = current;
    }

    private CreditTermEntityFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = customerAccountController.getCurrent().getCreditTerm();
        return "View";
    }

    public void prepareCreate() {
        current = new CreditTermEntity();
    }

    public String useDefaultTerm() {
        CreditTermEntity defaultTerm = getFacade().getDefaultCreditTerm();
        customerAccountController.getCurrent().setCreditTerm(defaultTerm);
        customerAccountController.createOrUpdate();

        defaultTerm.getCustomerAccounts().add(customerAccountController.getCurrent());
        getFacade().edit(defaultTerm);
        current = defaultTerm;

        return "/entities/customerAccountEntity/View.xhmtl";
    }

    public String createAndAssign() {
        try {
            current.created(getLoginPerson());
            getFacade().create(current);
            customerAccountController.getCurrent().setCreditTerm(current);
            customerAccountController.createOrUpdate();

            current.getCustomerAccounts().add(customerAccountController.getCurrent());
            getFacade().edit(current);

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CreditTermEntityCreated"));

            return "/entities/customerAccountEntity/View.xhmtl";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
//        current = (CreditTermEntity)getItems().getRowData();
        return "Edit";
    }

    public String update() {
        try {
            System.out.println("updating credit term: " + current.childToString());
            System.out.println("old credit term: " + oldCreditTerm.childToString());
            for (CustomerAccountEntity account : current.getCustomerAccounts()) {
                account.setCreditBalance(current.getCreditLimit() - (oldCreditTerm.getCreditLimit() - account.getCreditBalance()));
                customerAccountController.setCurrent(account);
                customerAccountController.update();
            }

            current.modified(getLoginPerson());
            getFacade().edit(current);
            System.out.println("updated credit term & account.");
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CreditTermEntityUpdated"));
            return "/entities/customerAccountEntity/View.xhmtl";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            e.printStackTrace();
            return null;
        }
    }

    public String performDestroy() {
        try {
            if (current.getIsDefaultTerm().equals("Default")) {
                throw new CannotDeleteDefaultCreditTermException("Cannot delete default credit term");
            }

            for (CustomerAccountEntity account : current.getCustomerAccounts()) {
                customerAccountController.setCurrent(account);
                customerAccountController.destroy();
            }

            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CreditTermEntityDeleted"));
        } catch (CannotDeleteDefaultCreditTermException e) {
            JsfUtil.addErrorMessage(e, e.getMessage());
            return null;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }

        return "/entities/customerAccountEntity/List.xhtml";
    }

    public List<CreditTermEntity> getItems() {
        if (items == null) {
            items = getFacade().findAll();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = CreditTermEntity.class)
    public static class CreditTermEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CreditTermEntityController controller = (CreditTermEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "creditTermEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof CreditTermEntity) {
                CreditTermEntity o = (CreditTermEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CreditTermEntityController.class.getName());
            }
        }
    }

    public CustomerAccountEntityController getCustomerAccountController() {
        return customerAccountController;
    }

    public void setCustomerAccountController(CustomerAccountEntityController customerAccountController) {
        this.customerAccountController = customerAccountController;
    }

    public CreditTermEntity getBlankCreditTerm() {
        System.out.println("getting blanck credit term");
        return new CreditTermEntity();
    }

    public CreditTermEntity getDeepCloneOfCurrentCreditTerm() {
        System.out.println("getting deep clone of current credit term");
        return new CreditTermEntity(current.getCreditLimit(),
                current.getMaxRepayTime(), current.getLateCharges(),
                current.getDiscountRepayTime(), current.getDiscount());
    }

    public CreditTermEntity getOldCreditTerm() {
        return oldCreditTerm;
    }

    public void setOldCreditTerm(CreditTermEntity oldCreditTerm) {
        System.out.println("setting old credit term: " + oldCreditTerm.childToString());
        this.oldCreditTerm = oldCreditTerm;
    }
}
